import numpy as np
import torch
import torch.nn as nn


# from torchsummary import summary
# device = torch.device('cpu')

class ConvBNLayer(nn.Module):
    def __init__(self, in_channels, out_channels, kernel, stride=1, act='ReLU'):
        super(ConvBNLayer, self).__init__()
        self.act_flag = act
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=2 if stride == (1, 1) else kernel, stride=stride, padding=(kernel - 1) // 2, dilation=2 if stride == (1, 1) else 1)
        self.bn = nn.BatchNorm2d(out_channels)
        self.act = nn.ReLU(True)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)
        if self.act_flag != 'None':
            x = self.act(x)
        return x


class Shortcut(nn.Module):
    def __init__(self, in_channels, out_channels, stride, is_first=False):
        super(Shortcut, self).__init__()
        self.use_conv = True
        if in_channels != out_channels or stride != 1 or is_first == True:
            if stride == (1, 1):
                self.conv = ConvBNLayer(in_channels, out_channels, 1, 1)
            else:
                self.conv = ConvBNLayer(in_channels, out_channels, 1, stride)
        else:
            self.use_conv = False

    def forward(self, x):
        if self.use_conv:
            x = self.conv(x)
        return x


class BottleneckBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride):
        super(BottleneckBlock, self).__init__()
        self.conv0 = ConvBNLayer(in_channels, out_channels, kernel=1)
        self.conv1 = ConvBNLayer(out_channels, out_channels, kernel=3, stride=stride)
        self.conv2 = ConvBNLayer(out_channels, out_channels * 4, kernel=1, act='None')
        self.short = Shortcut(in_channels, out_channels * 4, stride=stride)
        self.out_channels = out_channels * 4
        self.relu = nn.ReLU(True)

    def forward(self, x):
        y = self.conv0(x)
        y = self.conv1(y)
        y = self.conv2(y)
        y = y + self.short(x)
        y = self.relu(y)
        return y


class BasicBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride, is_first):
        super(BasicBlock, self).__init__()
        self.conv0 = ConvBNLayer(in_channels, out_channels, kernel=3, stride=stride)
        self.conv1 = ConvBNLayer(out_channels, out_channels, kernel=3, act='None')
        self.short = Shortcut(in_channels, out_channels, stride, is_first)
        self.out_chanels = out_channels
        self.relu = nn.ReLU(True)

    def forward(self, x):
        y = self.conv0(x)
        y = self.conv1(y)
        y = y + self.short(x)
        y = self.relu(y)
        return y


class ResNet_FPN(nn.Module):
    def __init__(self, in_channels=1, layers=50, **kwargs):
        super(ResNet_FPN, self).__init__()
        supported_layers = {
            18: {
                'depth': [2, 2, 2, 2],
                'block_class': BasicBlock
            },
            34: {
                'depth': [3, 4, 6, 3],
                'block_class': BasicBlock
            },
            50: {
                'depth': [3, 4, 6, 3],
                'block_class': BottleneckBlock
            },
            101: {
                'depth': [3, 4, 23, 3],
                'block_class': BottleneckBlock
            },
            152: {
                'depth': [3, 8, 36, 3],
                'block_class': BottleneckBlock
            }
        }
        stride_list = [(2, 2), (2, 2,), (1, 1), (1, 1)]
        num_filters = [64, 128, 256, 512]
        self.depth = supported_layers[layers]['depth']
        self.F = []
        self.conv = ConvBNLayer(in_channels=in_channels, out_channels=64, kernel=7, stride=2)  # 64*256 ->32*128

        # self.block_list = []
        self.block_list = nn.ModuleList()
        in_ch = 64
        if layers >= 50:
            for block in range(len(self.depth)):
                for i in range(self.depth[block]):
                    self.block_list.append(BottleneckBlock(in_channels=in_ch, out_channels=num_filters[block], stride=stride_list[block] if i == 0 else 1))
                    in_ch = num_filters[block] * 4
                    # self.block_list.append(block_list)
                # self.F.append(block_list)
        else:
            for block in range(len(self.depth)):
                for i in range(self.depth[block]):
                    if i == 0 and block != 0:
                        stride = (2, 1)
                    else:
                        stride = (1, 1)
                    basic_block = BasicBlock(in_channels=in_ch, out_channels=num_filters[block], stride=stride_list[block] if i == 0 else 1, is_first=block == i == 0)
                    in_ch = basic_block.out_chanels
                    self.block_list.append(basic_block)

        out_ch_list = [in_ch // 4, in_ch // 2, in_ch]
        self.base_block = nn.ModuleList()
        self.conv_trans = []
        self.bn_block = []
        for i in [-2, -3]:
            in_channels = out_ch_list[i + 1] + out_ch_list[i]
            self.base_block.append(nn.Conv2d(in_channels, out_ch_list[i], kernel_size=1))  # 进行升通道
            self.base_block.append(nn.Conv2d(out_ch_list[i], out_ch_list[i], kernel_size=3, padding=1))  # 进行合并
            self.base_block.append(nn.Sequential(nn.BatchNorm2d(out_ch_list[i]), nn.ReLU(True)))
        self.base_block.append(nn.Conv2d(out_ch_list[i], 512, kernel_size=1))
        # self.base_block = [item.to(device) for item in self.base_block]
        # self.base_block = nn.Sequential(*self.base_block)
        self.out_channels = 512

        # self.pooling = nn.MaxPool2d(kernel_size=2,stride=2,padding=1)

    def forward(self, x):
        # print('2222222')
        x = self.conv(x)
        # print(x.size())
        # x = self.pooling(x)
        # print(x.size())
        # print(self.conv.conv.weight.device)
        # print('3333333')
        fpn_list = []
        F = []
        for i in range(len(self.depth)):
            fpn_list.append(np.sum(self.depth[:i + 1]))
        # print(self.block_list)
        # print(fpn_list)
        # print(x.size())
        for i, block in enumerate(self.block_list):
            # print(block)
            # block = block.to(device)
            # print(block.conv0.conv.weight.device)
            # print(x.size())
            x = block(x)

            for number in fpn_list:
                if i + 1 == number:
                    F.append(x)
        base = F[-1]

        # print(base.size())

        j = 0
        for i, block in enumerate(self.base_block):
            if i % 3 == 0 and i < 6:
                j = j + 1
                b, c, h, w = F[-j - 1].size()
                if [h, w] == list(base.size()[2:]):
                    base = base
                else:
                    base = self.conv_trans[j - 1](base)
                    base = self.bn_block[j - 1](base)
                base = torch.cat([base, F[-j - 1]], dim=1)
                # print(base.size())     #只融合了后3层的特征，采取的融合方式是
            base = block(base)
        return base


def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)


def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)


class res_block(nn.Module):
    def __init__(self, in_planes, planes, stride=1, downsample=None):
        super(res_block, self).__init__()
        self.conv1 = conv1x1(in_planes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        if self.downsample is not None:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out


class ResNet_50(nn.Module):
    """
    64 x 256
    32 x 128
    16 x 64
    8  x 32
    """

    def __init__(self, n_group=1):
        super(ResNet_50, self).__init__()
        self.n_group = n_group

        in_channels = 3
        self.layer0 = nn.Sequential(
            nn.Conv2d(in_channels, 32, kernel_size=(3, 3), stride=2, padding=1, bias=False),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True))

        self.inplanes = 32
        self.layer1 = self._make_layer(32, 3, [1, 1])  # [32, 128]
        self.layer2 = self._make_layer(64, 4, [2, 2])  # [16, 64]
        self.layer3 = self._make_layer(128, 6, [1, 1])  # [16, 64]
        self.layer4 = self._make_layer(256, 6, [2, 2])  # [8, 32]
        self.layer5 = self._make_layer(512, 3, [1, 1])  # [8, 32]

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, planes, blocks, stride):
        downsample = None
        if stride != [1, 1] or self.inplanes != planes:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes, stride),
                nn.BatchNorm2d(planes))

        layers = []
        layers.append(res_block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes
        for _ in range(1, blocks):
            layers.append(res_block(self.inplanes, planes))
        return nn.Sequential(*layers)

    def forward(self, x):
        x0 = self.layer0(x)  # 32 x 128
        x1 = self.layer1(x0)  # 32 x 128
        x2 = self.layer2(x1)  # 16 x 64
        x3 = self.layer3(x2)  # 16 x 64
        x4 = self.layer4(x3)  # 8  x 32
        x5 = self.layer5(x4)  # 8 x 32

        # cnn_feat = x5 [x5,x3,x1]
        return [x5, x4, x3]  # 512,256,128


if __name__ == '__main__':
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    # res_fpn = ResNet_FPN(3,50)
    res = ResNet_50().to(device)
    # res_fpn = res_fpn.to(device)
    print(res)
    for i in range(500):
        x = torch.randn([4, 3, 64, 256]).to(device)
        # output = res_fpn(x)
        output = res(x)
        print(output[0].size())

#    summary(res_fpn,input_size=(1,64,256),batch_size=-1)
#    print(list(res_fpn.named_parameters()))

#    bb =  BottleneckBlock(512,512,1).cuda()
#    bb2 = BottleneckBlock(2048,512,1).cuda()


#    output = res_fpn(x)
